package api

import (
	"context"
	"doctor_srv/global"
	"doctor_srv/model/dao"
	pb "doctor_srv/proto"
	"encoding/json"
	"fmt"
	"github.com/winksai/utils/pagination"
	"time"
)

type DoctorServer struct {
	pb.UnimplementedDoctorServer
}

func (d *DoctorServer) HospitalList(ctx context.Context, req *pb.HospitalRequest) (resp *pb.HospitalResponse, err error) {

	var result []*pb.Hospital
	key := fmt.Sprintf("hospital:page_%d:page_size_%d", req.Page, req.PageSize)

	data, err := global.RedisClient.Get(context.Background(), key).Result()
	if err == nil && data != "" {
		json.Unmarshal([]byte(data), &result)
		fmt.Println("redis展示")
		return &pb.HospitalResponse{Hospitals: result}, nil
	}
	if req.PageSize > 5 {
		req.PageSize = 5
	}
	Pagination := pagination.Pagination{
		Page:     int(req.Page),
		PageSize: int(req.PageSize),
	}
	offset := Pagination.Offset()
	limit := Pagination.Limit()
	list := dao.GetHospitalsList(offset, limit)

	for _, hospital := range list {
		result = append(result, &pb.Hospital{
			Id:          int32(hospital.ID),
			Name:        hospital.Name,
			Description: hospital.Description,
			Intro:       hospital.Intro,
			Image:       hospital.Image,
		})
	}
	marshal, err := json.Marshal(result)

	global.RedisClient.Set(context.Background(), key, marshal, time.Minute*30)
	fmt.Println("mysql展示")
	return &pb.HospitalResponse{Hospitals: result}, nil
}
